package top.pengdong.pictureShare.userAuth.controller;

import java.util.Arrays;
import java.util.List;
import java.util.Map;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import top.pengdong.pictureShare.common.model.PageUtils;
import top.pengdong.pictureShare.common.model.R;
import top.pengdong.pictureShare.common.model.SysConstant;
import top.pengdong.pictureShare.userAuth.entity.TAuthEntity;
import top.pengdong.pictureShare.userAuth.entity.TRoleAuthEntity;
import top.pengdong.pictureShare.userAuth.entity.TRoleEntity;
import top.pengdong.pictureShare.userAuth.service.TAuthService;
import top.pengdong.pictureShare.userAuth.service.TRoleAuthService;
import top.pengdong.pictureShare.userAuth.service.TRoleService;


/**
 * 权限表 对于权限表的增加 和删除 ，以及查看列表信息1，进行修改操作
 *
 * @author chenshun
 * @email pengshi12138@outlook.com
 * @date 2022-04-18 18:23:15
 */
@RestController
@RequestMapping("api/auth")
public class TAuthController {
    @Autowired
    private TAuthService tAuthService;

    @Autowired
    private TRoleAuthService tRoleAuthService;


    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 列表
     */
    @RequestMapping("/list")
    public R list(@RequestParam Map<String, Object> params){
        PageUtils page = tAuthService.queryPage(params);

        return R.ok().put("page", page);
    }

    /**
     * 保存
     */
    @RequestMapping("/save")
    public R save(@RequestBody TAuthEntity tAuth){
		tAuthService.saveWithRoles(tAuth);

        return R.ok();
    }

    /**
     * 删除
     */
    @RequestMapping("/delete")
    public R delete(@RequestBody Long[] ids){
        List<TAuthEntity> list = tAuthService.listByIds(Arrays.asList(ids));
        //TODO 处理白名单操作
        for (TAuthEntity tAuthEntity : list) {
            if (tAuthEntity.getIsMenu() == 2) {
                List<String> white = (List<String>) redisTemplate.opsForValue().get(SysConstant.OAUTH_URLS);
                white.remove(tAuthEntity.getPath());
                redisTemplate.opsForValue().set(SysConstant.OAUTH_URLS, white);
            }
            else redisTemplate.opsForHash().delete(SysConstant.OAUTH_URLS, tAuthEntity.getPath());
        }
		tAuthService.removeByIds(Arrays.asList(ids));
        tRoleAuthService.remove(new QueryWrapper<TRoleAuthEntity>().in("auth_id", Arrays.asList(ids)));

        return R.ok("删除成功");
    }

}
